<!--
/**
* @author xuyh0817
* @email xuyh0817@foxmail.com
* @date 2022-02-22 01:23
* @version 2.0.0
* @doc todo
* @website todo
* @remark  如果要分发源码，需在本文件顶部保留此文件头信息！！
*/
-->
<template>
  <a-modal
    title="新增校检规则"
    :visible="visible"
    :footer="null"
    centered
    :mask-closable="false"
    destroy-on-close
    width="50%"
    @cancel="closeHandler"
  >
    <x-render-form
      v-if="visible"
      ref="xRenderDesignRuleForm"
      v-model="formData"
      :form-options="formOptions"
      @change="formChangeHandler"
    />
  </a-modal>
</template>

<script>
import { cloneDeep } from 'lodash'
import FormOptions from './options'

export default {
  name: 'XDesignFormItemRules',
  inject: ['xDesignForm'],
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {}
    }
  },
  computed: {
    formOptions: {
      get() {
        return cloneDeep(FormOptions)
      }
    }
  },
  methods: {
    closeHandler() {
      this.$emit('update:visible', false)
      this.formData = {
        type: 'string'
      }
    },
    formAddHandler() {
      const formData = this.formData
      const rule = {}
      for (const key in formData) {
        const value = formData[key]
        if (value) {
          rule[key] = value
        }
      }
      this.$emit('add-rule', rule)
      this.formData = {
        type: 'string'
      }
    },
    formChangeHandler({ prop, value }) {
      if (prop === 'type') {
        const xRenderDesignRuleForm = this.$refs.xRenderDesignRuleForm
        if (['string', 'number', 'float', 'integer', 'hex'].includes(value)) {
          xRenderDesignRuleForm.showFields('min', 'max', 'len')
        } else {
          xRenderDesignRuleForm.hideFields('min', 'max', 'len')
        }
        if (['string', 'url', 'email'].includes(value)) {
          xRenderDesignRuleForm.showFields('pattern')
        } else {
          xRenderDesignRuleForm.hideFields('pattern')
        }
      }
    }
  }
}
</script>
